<?php
function nsubstr($needle, $haystack, $n_occurrence)
{
    // After exploding by $needle, every entry in $arr except (possibly) part of the last entry should have its content returned.
    $arr = explode($needle,$haystack,$n_occurrence);
    // Examine last entry in $arr. If it contains $needle, cut out all text except for the text before $needle.
    $last = count($arr) - 1;
    $pos_in_last = strpos($arr[$last],$needle);

    if ($pos_in_last !== false)
        $arr[$last] = substr($arr[$last],0,$pos_in_last);

    return implode($needle,$arr);
}

?>
